<?php

namespace app\admin\controller\dahui;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 企业补缴管理
 *
 * @icon fa fa-circle-o
 */
class Qiyebujiao extends Backend
{
    
    /**
     * Qiyebujiao模型对象
     * @var \app\admin\model\dahui\Qiyebujiao
     */
    protected $model = null;

    protected $searchFields = 'id,idnumber,ownedcompany,qiyekehu.name,qiyekehu.mobile';

    protected $noNeedRight = ['changebjstatus', 'index1list', 'index1'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahui\Qiyebujiao;
        $this->view->assign("businesstypeList", $this->model->getBusinesstypeList());
        $this->view->assign("overduestatusList", $this->model->getOverduestatusList());

        $this->assignconfig('audit', $this->auth->check('dahui/dingdan/audit'));
        $this->assignconfig('luru', $this->auth->check('dahui/dingdan/luru'));
        $this->assignconfig('caozuo', $this->auth->check('dahui/dingdan/caozuo'));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['qiyekehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $money = $this->model
                ->with(['qiyekehu'])
                ->where($where)
                ->order($sort, $order)
                ->sum('paymentamount');

            $list = $this->model
                    ->with(['qiyekehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function importstr($one) {

        return "' ".$one;
    }

    //企业补缴明细表单
    public function index1()
    {
        $idnumber = $this->request->get("idnumber", '');
        $row = \app\admin\model\dahui\Qiyekehu::where('idnumber', $idnumber)->find();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params = $this->setquanxianlog($params);
            $result = $row->allowField(true)->save($params);
            $this->success('修改成功');
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //企业补缴明细-列表
    public function index1list() {

        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $idnumber = $this->request->get("idnumber", '');
            $list = $this->model
                ->where('idnumber', $idnumber)
                ->select();

            $list = collection($list)->toArray();

            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
//                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $row = $this->model
                        ->where('overdueyear', $params['overdueyear'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    $params = $this->setquanxianlog($params);
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        return $this->view->fetch();
    }

    /**
     * 编辑 企业补缴
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->where('id', $ids)
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $row = $this->setquanxianlog2($row);
                if (isset($params['supplementarynote'])) {
                    $row->supplementarynote = $params['supplementarynote'];
                    $row->save();
                    $this->success();
                }

                if (isset($params['monthspaid'])) {
                    $row->monthspaid = $params['monthspaid'];
                    $row->save();
                    $this->success();
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $this->error(__('未找到企业客户！'));
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
            $row['bankcardnumber'] = $kehu->bankcardnumber;
            $row['address0'] = $kehu->address0;
            $row['address1'] = $kehu->address1;
            $row['note'] = $kehu->note;
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 补缴状态++
     */
    //http://dahui.test/admin/dahui/qiyebujiao/changebjstatus
    public function changebjstatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->overduestatus == '未办理') {
            $row->overduestatus = '已办理';
        } else if ($row->overduestatus == '已办理') {
            $row->overduestatus = '部分失败';
        } else if ($row->overduestatus == '部分失败') {
            $row->overduestatus = '未办理';
        }

        $row = $this->setquanxianlog2($row);


        $row->save();
        $this->success("补缴状态修改成功", null, ['overduestatus' => $row->overduestatus]);
    }

    public function import()
    {
        parent::import();
    }

    //设置权限记录
    function setquanxianlog($params)
    {
        if (!$params) {
            return $params;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $params['auditman'] = $this->auth->nickname;
        } else if ($luru) {
            $params['luruman'] = $this->auth->nickname;
        } else if ($caozuo) {
            $params['opman'] = $this->auth->nickname;
        }

        return $params;
    }

    function setquanxianlog2($row)
    {
        if (!$row) {
            return $row;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $row->auditman = $this->auth->nickname;
        } else if ($luru) {
            $row->luruman = $this->auth->nickname;
        } else if ($caozuo) {
            $row->opman= $this->auth->nickname;
        }

        return $row;
    }
}
